//
//  YJUserEditViewController.m
//  AndCampus
//
//  Created by 史宵宵 on 2017/11/17.
//  Copyright © 2017年 史宵宵. All rights reserved.
//
// 老师：MTM1MjI4NDk1NjY6MTUxMjAxNTA0OTM2Njo1OWJhZjhlMTE1NTM0NmYyYTY1MzMyNzc3ZmE3Yjk4MA==

#import "YJUserEditViewController.h"
#import "loginTextField.h"
#import "MKToolDatePicker.h"
#import "TZImagePickerController.h"
#import "GLPickerView.h"

@interface YJUserEditViewController ()<UITextFieldDelegate,UITextViewDelegate,MKToolDatePickerDelegate,TZImagePickerControllerDelegate>

@property (nonatomic,strong) NSMutableArray *textArray; //

@property (nonatomic,strong) NSMutableArray *textValeArray; //数组的值 数组

@property (nonatomic,weak) UITextField *teacherTF;//显示班主任，任课老师，与时老师的textField
@property (nonatomic,weak) UITextField *teacherNameTF;
@property (nonatomic,weak) UITextField *teacherEmailTF;

@property (nonatomic,weak) UITextField *studentStarTF;//星座textField
@property (nonatomic,weak) UITextField *studentDataTF;//选择日期textField
@property (nonatomic, strong) MKToolDatePicker *toolDatePicker;

@property (nonatomic,weak) UIImage *logoImage;//头像的image
@property (nonatomic,weak) UIImageView *logoImageView;//展示头像的imageView
@property (nonatomic,weak) JSTextView *releaseContentTextView;
@end

@implementation YJUserEditViewController
- (NSMutableArray *)textArray{
    if (!_textArray) {
        _textArray = [NSMutableArray array];
    }
    return _textArray;
}
- (NSMutableArray *)textValeArray{
    if (!_textValeArray) {
        _textValeArray = [NSMutableArray array];
    }
    return _textValeArray;
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (self.userEditRole == KMyCenterEditStudent || self.userEditRole == KMyCenterEditPerson || self.userEditRole == KMyCenterEditTeacher) {
        [self.navigationController setNavigationBarHidden:NO animated:YES];
    }else{
        [self.navigationController setNavigationBarHidden:YES animated:YES];
    }
    //    [Global setStatusBarBackgroundColor:[UIColor clearColor]];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    if (self.userEditRole == KMyCenterEditStudent || self.userEditRole == KMyCenterEditPerson || self.userEditRole == KMyCenterEditTeacher) {
        [self.navigationController setNavigationBarHidden:NO animated:YES];
    }else{
        [self.navigationController setNavigationBarHidden:YES animated:YES];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.tableView.frame = CGRectMake(0, 0, kScreenW, kScreenH);
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.title = @"编辑信息";
    if (self.userEditRole == KUserEditStudent || self.userEditRole == KMyCenterEditStudent) {
        self.textArray = [NSMutableArray arrayWithArray:@[@"请输入您的昵称",@"请输入您的邮箱",@"请输入您的出生日期",@"星座"]];
        self.textValeArray = [NSMutableArray arrayWithObjects:@"",@"",@"",@"", nil];
        if (!strIsEmpty([JHUserInfo getUserInfo].birthdate)) {
            [self.textValeArray replaceObjectAtIndex:2 withObject:[JHUserInfo getUserInfo].birthdate];
        }
        if (!strIsEmpty([JHUserInfo getUserInfo].constellation)) {
            [self.textValeArray replaceObjectAtIndex:3 withObject:[JHUserInfo getUserInfo].constellation];
        }
    }else if (self.userEditRole == KUserEditPerson || self.userEditRole == KMyCenterEditPerson) {
        self.textArray = [NSMutableArray arrayWithArray:@[@"请输入您的昵称",@"请输入您的邮箱"]];
        self.textValeArray = [NSMutableArray arrayWithObjects:@"",@"", nil];
        
    }else if (self.userEditRole == KUserEditTeacher || self.userEditRole == KMyCenterEditTeacher) {
        self.textArray = [NSMutableArray arrayWithArray:@[@"请输入您的昵称",@"请输入您的邮箱",@"请选择职能",@"自我介绍"]];
        self.textValeArray = [NSMutableArray arrayWithObjects:@"",@"",@"",@"", nil];
        if (!strIsEmpty([JHUserInfo getUserInfo].role_type)) {
            [self.textValeArray replaceObjectAtIndex:2 withObject:[JHUserInfo getUserInfo].role_type];
        }
        if (!strIsEmpty([JHUserInfo getUserInfo].des)) {
            [self.textValeArray replaceObjectAtIndex:3 withObject:[JHUserInfo getUserInfo].des];
        }
    }
    if (!strIsEmpty([JHUserInfo getUserInfo].nick_name)) {
        [self.textValeArray replaceObjectAtIndex:0 withObject:[JHUserInfo getUserInfo].nick_name];
    }
    if (!strIsEmpty([JHUserInfo getUserInfo].email)) {
        [self.textValeArray replaceObjectAtIndex:1 withObject:[JHUserInfo getUserInfo].email];
    }
    [self creatView];
}

- (void)creatView{
    UIView *headView = [[UIView alloc]init];
    headView.backgroundColor = [UIColor whiteColor];
    headView.frame = CGRectMake(0, 0, kScreenW, kScreenH / 9 + 20 + kScreenW / 5 + 10);
    self.tableView.tableHeaderView = headView;
//    if (self.userEditRole == KMyCenterEditStudent || self.userEditRole == KMyCenterEditPerson || self.userEditRole == KMyCenterEditTeacher) {
//
//    }else{
//        UIButton *skipButton = [[UIButton alloc]init];
//        [skipButton setTitle:@"跳过" forState:UIControlStateNormal];
//        [skipButton setTitleColor:KTEXTMAINCOLOR forState:UIControlStateNormal];
//        skipButton.frame = CGRectMake(kScreenW - 70, 10, 60, 20);
//        [skipButton addTarget:self action:@selector(skipEnterMain) forControlEvents:UIControlEventTouchUpInside];
//        [headView addSubview:skipButton];
//    }
    
    
//    UIButton *backButton = [[UIButton alloc]init];
//    backButton.frame = CGRectMake(10, 30, 50, 50);
//    [backButton setImage:[UIImage imageNamed:@"black_back"] forState:UIControlStateNormal];
//    [backButton addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
//    [headView addSubview:backButton];
    
//    UIImageView *iconImageView = [[UIImageView alloc]init];
//    iconImageView.frame = CGRectMake(kScreenW / 3, kScreenH / 9, kScreenW / 3 , kScreenW / 5 );
//    iconImageView.contentMode = UIViewContentModeScaleAspectFill;
//    iconImageView.image = [UIImage imageNamed:@"Login_sign"];
//    [headView addSubview:iconImageView];
    
    UIImageView *logoImageView = [[UIImageView alloc]init];
    logoImageView.frame = CGRectMake((kScreenW - kScreenW/5)/2, kScreenH / 9 + 20, kScreenW / 5 , kScreenW / 5 );
    logoImageView.contentMode = UIViewContentModeScaleAspectFill;
    if (!strIsEmpty([JHUserInfo getUserInfo].icon)) {
        [logoImageView sd_setImageWithURL:[NSURL URLWithString:[JHUserInfo getUserInfo].icon] placeholderImage:KDEFAULTHEAD];
    }else{
        logoImageView.image = KDEFAULTHEAD;
    }
    logoImageView.backgroundColor = [UIColor yellowColor];
    logoImageView.clipsToBounds = YES;
    logoImageView.layer.cornerRadius = kScreenW/5/2;
    [headView addSubview:logoImageView];
    logoImageView.userInteractionEnabled = YES;
    [logoImageView addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(realeaseAddImageTap)]];
    self.logoImageView = logoImageView;

    UIView *footView = [[UIView alloc]init];
    footView.backgroundColor = [UIColor whiteColor];
    footView.frame = CGRectMake(0, 0, kScreenW, 150);
    self.tableView.tableFooterView = footView;
    
    CompleteButton *loginButton = [[CompleteButton alloc]initWithFrame:CGRectMake(20, 20, kScreenW - 40, 40) bgColor:KBACKNAVIGATIONCOLOR tColor:[UIColor whiteColor] text:@"确定"];
    [loginButton addTarget:self action:@selector(sureUserInfo) forControlEvents:UIControlEventTouchUpInside];
    [footView addSubview:loginButton];
}
-(void)realeaseAddImageTap
{
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
    // You can get the photos by block, the same as by delegate.
    // 你可以通过block或者代理，来得到用户选择的照片.
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos,NSArray *assets,BOOL isSelectOriginalPhoto){
        self.logoImageView.image = photos[0];
        self.logoImage = photos[0];
    }];
    [self presentViewController:imagePickerVc animated:YES completion:nil];
    
}
- (NSInteger )numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.textArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *CellIdentifier = @"last";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (!cell) {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;

        if ((self.userEditRole == KUserEditTeacher || self.userEditRole == KMyCenterEditTeacher) && indexPath.row == 3) {
            JSTextView *releaseContentTextView = [[JSTextView alloc] initWithFrame:CGRectMake(20, 5, kScreenW - 40, 100)];
            releaseContentTextView.tag = 2000 + indexPath.row;
            releaseContentTextView.font = [UIFont systemFontOfSize:16];
            releaseContentTextView.textColor = KTEXTMAINCOLOR;
            releaseContentTextView.delegate = self;
            releaseContentTextView.autocorrectionType = UITextAutocorrectionTypeNo;  //取消纠错
            releaseContentTextView.autocapitalizationType = UITextAutocapitalizationTypeNone;  //取消首字母大写
            releaseContentTextView.returnKeyType = UIReturnKeyDefault;  //return改成done
            releaseContentTextView.myPlaceholder = self.textArray[indexPath.row];
            releaseContentTextView.clipsToBounds = YES;
            releaseContentTextView.layer.cornerRadius = 2;
            releaseContentTextView.layer.borderColor = [UIColor lightGrayColor].CGColor;
            releaseContentTextView.layer.borderWidth = 1;
            releaseContentTextView.text = self.textValeArray[indexPath.row];
            [cell.contentView addSubview:releaseContentTextView];
        }else{
            loginTextField *loginTF = [[loginTextField alloc]initWithFrame:CGRectMake(20, 5, kScreenW - 40 , 40) placeholder:self.textArray[indexPath.row] imageStr:@""];
            loginTF.delegate = self;
            loginTF.tag = 1000 + indexPath.row;
            loginTF.text = self.textValeArray[indexPath.row];
            [cell.contentView  addSubview:loginTF];
        }
    }
    loginTextField *loginTF = [cell.contentView viewWithTag:1000 + indexPath.row];
    if (indexPath.row == 1) {
        loginTF.keyboardType = UIKeyboardTypeURL;
    }
    if ((self.userEditRole == KUserEditStudent || self.userEditRole == KMyCenterEditStudent) && indexPath.row == 2) {
        self.studentDataTF = loginTF;
        MKToolDatePicker *tool = [[MKToolDatePicker alloc]init];
        self.toolDatePicker = tool;
        tool.delegate = self; // 设置代理
        [self.toolDatePicker datePickerOnTextField:self.studentDataTF];
    }
    if ((self.userEditRole == KUserEditStudent || self.userEditRole == KMyCenterEditStudent) && indexPath.row == 3) {
        self.studentStarTF.userInteractionEnabled = NO;
        self.studentStarTF = loginTF;
    }
    if ((self.userEditRole == KUserEditTeacher || self.userEditRole == KMyCenterEditTeacher) && indexPath.row == 0) {
        self.teacherNameTF = loginTF;
    }
    if ((self.userEditRole == KUserEditTeacher || self.userEditRole == KMyCenterEditTeacher) && indexPath.row == 1) {
        self.teacherEmailTF = loginTF;
    }
    if ((self.userEditRole == KUserEditTeacher || self.userEditRole == KMyCenterEditTeacher) && indexPath.row == 2) {
        self.teacherTF = loginTF;
        self.teacherTF.text = [JHUserInfo getUserInfo].course;
    }
    if ((self.userEditRole == KUserEditTeacher || self.userEditRole == KMyCenterEditTeacher) && indexPath.row == 3) {
        JSTextView *releaseContentTextView = [cell.contentView viewWithTag:2000 + indexPath.row];
        self.releaseContentTextView = releaseContentTextView;
    }
    
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if ((self.userEditRole == KUserEditTeacher || self.userEditRole == KMyCenterEditTeacher)  && indexPath.row == 3) {
        return 110;
    }
    return 50;
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = [[UIView alloc]init];
    view.frame = CGRectMake(0, 0, kScreenW, 0.01);
    view.backgroundColor = [UIColor whiteColor];
    
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.01f;
}
- (void)textFieldDidBeginEditing:(UITextField *)textField{
//    [self.teacherNameTF endEditing:YES];
    if ((self.userEditRole == KUserEditTeacher || self.userEditRole == KMyCenterEditTeacher )&& textField.tag - 1000 == 2) {
        
//        [[UIApplication sharedApplication] sendAction:@selector(hideKeyboard) to:nil from:nil forEvent:nil];
//        [self.teacherNameTF endEditing:YES];
//        [self.teacherEmailTF endEditing:YES];
//        [self.teacherNameTF resignFirstResponder];
//        [self.teacherEmailTF resignFirstResponder];
//        [self.teacherNameTF canResignFirstResponder];
//        [self.teacherEmailTF canResignFirstResponder];
        [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
        [textField endEditing:YES];
        GLPickerView *pickView= [[GLPickerView alloc]initDatePackerWithDataArray:@[@"班主任",@"心理老师",@"生涯老师",@"任课老师",@"其他"] Response:^(NSString *title) {
            self.teacherTF.text = title;
        }];
        [pickView show];
    }
}
- (void)hideKeyboard{
    
    [self.teacherNameTF endEditing:YES];
    [self.teacherEmailTF endEditing:YES];
    [self.teacherNameTF resignFirstResponder];
    [self.teacherEmailTF resignFirstResponder];
    [self.teacherNameTF canResignFirstResponder];
    [self.teacherEmailTF canResignFirstResponder];
    
    [self.view endEditing:YES];
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField;
{
    [textField endEditing:YES];
    [textField resignFirstResponder];
    return YES;
}
-(void)textFieldDidEndEditing:(UITextField *)textField
{
    [self.textValeArray replaceObjectAtIndex:textField.tag - 1000 withObject:textField.text];
    [textField resignFirstResponder];
}
- (void)toolDatePicker:(MKToolDatePicker *)toolDatePicker onView:(UITextField *)textField didClickedDoneWithDate:(NSDate *)date{
    NSDateFormatter *fmt = [[NSDateFormatter alloc]init];
    fmt.dateFormat = @"yyyy-MM-dd";
    NSString *dateStr = [fmt stringFromDate:date];
    self.studentDataTF.text = dateStr;
    self.studentStarTF.text = [self getAstroWithMonth:[[dateStr substringWithRange:NSMakeRange(5, 2)] intValue] day:[[dateStr substringFromIndex:8]intValue]];
}
-(NSString *)getAstroWithMonth:(int)m day:(int)d{
    
    NSString *astroString = @"魔羯水瓶双鱼白羊金牛双子巨蟹狮子处女天秤天蝎射手魔羯";
    NSString *astroFormat = @"102123444543";
    NSString *result;
    
    if (m<1||m>12||d<1||d>31){
        return @"错误日期格式!";
    }
    
    if(m==2 && d>29)
    {
        return @"错误日期格式!!";
    }else if(m==4 || m==6 || m==9 || m==11) {
        
        if (d>30) {
            return @"错误日期格式!!!";
        }
    }
    
    result=[NSString stringWithFormat:@"%@",[astroString substringWithRange:NSMakeRange(m*2-(d < [[astroFormat substringWithRange:NSMakeRange((m-1), 1)] intValue] - (-19))*2,2)]];
    
    
    return result;
}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView*)pickerView
{
    return 1;
}

#pragma mark - 确定
- (void)sureUserInfo{
    [self.tableView endEditing:YES];
    if (strIsEmpty(self.textValeArray[0])) {
        [Global showActivityWithView:self.view withText:@"请输入昵称"];
        return;
    }
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    [dic setValue:[Global getUserTokenInfo] forKey:@"token"];   //用户认证
    [dic setValue:self.textValeArray[0] forKey:@"nickName"];   //昵称
    if (!strIsEmpty(self.textValeArray[1])) {
        [dic setValue:self.textValeArray[1] forKey:@"email"];   //邮箱
    }
    if (!strIsEmpty(self.studentDataTF.text)) {
        [dic setValue:self.studentDataTF.text forKey:@"birthdate"];   //出生年月
    }
    if (!strIsEmpty(self.studentStarTF.text)) {
        [dic setValue:self.studentStarTF.text forKey:@"constellation"];   //星座
    }
    if (!strIsEmpty(self.teacherTF.text)) {
        [dic setValue:self.teacherTF.text forKey:@"course"];   //学科
    }
    if (!strIsEmpty(self.releaseContentTextView.text)) {
        [dic setValue:self.releaseContentTextView.text forKey:@"describe"];
    }
    NSData *data = UIImageJPEGRepresentation(self.logoImage, 1.0f);
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:[JSPathUtil urlAppApiEditProfile] parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        if (self.logoImage) {
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            // 设置时间格式
            formatter.dateFormat = @"yyyyMMddHHmmss";
            NSString *str = [formatter stringFromDate:[NSDate date]];
            NSString *fileName = [NSString stringWithFormat:@"%@.jpeg", str];
            [formData appendPartWithFileData:data name:@"file" fileName:fileName mimeType:@"image/jpeg"];
        }
    } error:nil];
   
    AFURLSessionManager *manager=[[AFURLSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    manager.responseSerializer=[AFHTTPResponseSerializer serializer];
    NSURLSessionUploadTask *uploadTask;
    uploadTask = [manager
                  uploadTaskWithStreamedRequest:request
                  progress:^(NSProgress * _Nonnull uploadProgress) {
                  }
                  completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
                      if (error) {
                          MyLog(@"Error: %@", error);
                      } else {
                          MyLog(@"%@ %@", response, responseObject);
                          [Global showActivityWithView:self.view withText:@"修改个人信息成功"];
                          [self saveCurrentUserInfo];
                          
                      }
                  }];
    
    [uploadTask resume];
}
- (void)saveCurrentUserInfo{
    YJNetWorkManger *yjNetWorkManger =  [YJNetWorkManger shareManager];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    [dic setValue:[Global getUserTokenInfo] forKey:@"token"];   //token
    
    [yjNetWorkManger requestType:POST andURL:[JSPathUtil urlAppApiGetCurrentUserInfo] andParmas:dic andComplition:^(id response, BOOL isuccess) {
        if (isuccess) {
            NSMutableDictionary *dic = [[NSMutableDictionary alloc]initWithDictionary:response];
            [JHUserInfo saveUserInfo:dic[@"userInfo"]];
            [[Global appdelegete] enterTheMainViewIndex:3];
        }
    }];
}
#pragma mark - 跳过
- (void)skipEnterMain{
    [[Global appdelegete] enterTheMainViewIndex:4];
}
//#define mark - 返回
//- (void)back{
//    [self.navigationController popViewControllerAnimated:YES];
//}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
